//
//  GQMVViewController.m
//  TingMusic
//
//  Created by sunny on 16/4/21.
//  Copyright © 2016年 sunny. All rights reserved.
//

#import "GQMVViewController.h"
#import "GQMVHeaderView.h"
#import "GQMVCell.h"
#import "GQMvListItem.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

typedef NS_ENUM(NSInteger, OrderType) {
    OrderTypeNew,
    OrderTypeHottest
    
    
};

@interface GQMVViewController ()
@property (nonatomic, strong)NSMutableArray *itemArray;
@property (nonatomic, strong)AVPlayer *player;
//播放顺序（最热。最新）
@property (nonatomic, assign)NSInteger order;
@end

static NSString *headerViewID = @"GQMVHeaderView";
static NSString *MVCellID = @"MVCell";

@implementation GQMVViewController

+ (instancetype)mvViewController
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(170, 150);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 20;
    layout.headerReferenceSize = CGSizeMake(GQUIScreenW, 40);
    GQMVViewController *mvVc = [[GQMVViewController alloc] initWithCollectionViewLayout:layout];
    return mvVc;
}

- (NSMutableArray *)itemArray
{
    if (!_itemArray ) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, GQGlobleTabBarHeight, 0);
    self.order = OrderTypeHottest;

//    监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HottestButtonClick) name:@"HottestButtonDidClickNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NewButtonClick) name:@"NewButtonDidClickNotification" object:nil];
    
//    注册
    [self.collectionView registerNib:[UINib nibWithNibName:@"GQMVCell" bundle:nil] forCellWithReuseIdentifier:MVCellID];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"GQMVHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID];

    self.collectionView.mj_header = [GQDIYRefreshHeader gq_headerWithRefreshingBlock:^{
        [self loadData];
    }];
    
    //    加载最新数据
    [self.collectionView.mj_header beginRefreshing];
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 设置刷新图片
    NSArray *refreshingImages = @[
                                  [UIImage imageNamed:@"dropdown_loading_01"],
                                  [UIImage imageNamed:@"dropdown_loading_02"],
                                  [UIImage imageNamed:@"dropdown_loading_03"]
                                  ];
    
    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    // 设置尾部
    self.collectionView.mj_footer = footer;
    
}

#pragma mark - 监听通知调用方法
- (void)NewButtonClick
{
    self.order = OrderTypeHottest;
    [self loadData];

}

- (void)HottestButtonClick
{
    self.order = OrderTypeNew;
    [self loadData];
}

#pragma mark - 加载最新数据
- (void)loadData
{
//    拼接字符串
    NSString *urlString1 = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.2.0&channel=xiaomi&operator=2&provider=11%2C12&method=baidu.ting.mv.searchMV&format=json&";
    NSString *urlString2 = [NSString stringWithFormat:@"order=%zd",self.order];
    NSString *urlString3 = @"&page_num=1&page_size=20&query=%E5%85%A8%E9%83%A8";
    NSString *urlString = [[urlString1 stringByAppendingString:urlString2] stringByAppendingString:urlString3];
    
//    发送网络请求
    [GQHttpRequest GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.itemArray = [GQMvListItem mj_objectArrayWithKeyValuesArray:responseObject[@"result"][@"mv_list"]];
        
        //        刷新表格
        [self.collectionView reloadData];
        
        //        结束刷新
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        结束刷新
        [self.collectionView.mj_header endRefreshing];
    }];
}


#pragma mark - 加载更多数据
- (void)loadMoreData
{
    static NSInteger page = 2;
    
    NSString *urlString1 = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.2.0&channel=xiaomi&operator=2&provider=11%2C12&method=baidu.ting.mv.searchMV&format=json&order=1&";
    NSString *urlString2 = [NSString stringWithFormat:@"page_num=%zd",page];
    NSString *urlString3 = @"&page_size=20&query=%E5%85%A8%E9%83%A8";
    NSString *urlString = [[urlString1 stringByAppendingString:urlString2] stringByAppendingString:urlString3];
    [GQHttpRequest GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSArray *arrayM = [GQMvListItem mj_objectArrayWithKeyValuesArray:responseObject[@"result"][@"mv_list"]];
        [self.itemArray addObjectsFromArray:arrayM];
        
        //        刷新表格
        [self.collectionView reloadData];
        
        //        结束刷新
        [self.collectionView.mj_footer endRefreshing];
        
        page ++;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        结束刷新
        [self.collectionView.mj_footer endRefreshing];
    }];
    
    
}

#pragma mark - collectionView的数据源和代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GQMVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MVCellID forIndexPath:indexPath];
    GQMvListItem *mvListItem = self.itemArray[indexPath.row];
    cell.mvListItem =mvListItem;
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader){
        
        GQMVHeaderView *headerV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewID forIndexPath:indexPath];
        reusableview = headerV;
    }
    
    return reusableview;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    取出对应cell
    GQMVCell *cell = (GQMVCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    NSString *urlString1 = @"http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.7.3.0&channel=xiaomi&operator=2&provider=11%2C12&method=baidu.ting.mv.playMV&format=json&";
    NSString *urlString2 = [NSString stringWithFormat:@"mv_id=%@&song_id=&definition=0",cell.mvListItem.mv_id];
//    拼接字符串
    NSString *urlString = [urlString1 stringByAppendingString:urlString2];
    
    [GQHttpRequest GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id  _Nullable responseObject) {
        
//        取出获取到的视频播放的URL链接
        NSString *playUrlString = responseObject[@"result"][@"files"][@"21"][@"file_link"];
        
        AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:playUrlString]];
        AVPlayerViewController * playerVc = [[AVPlayerViewController alloc]init];
        playerVc.player = player;
        self.player = player;
        [player play];
        
        [self presentViewController:playerVc animated:YES completion:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        
    }];
    
}

- (void)dealloc
{
//    移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
